import os
import traceback

from flask import Blueprint, jsonify, request
from sqlalchemy import or_

from application import app, db
from models import AdvertiseImage

adv_bp = Blueprint('adv_bp', __name__)


# 获取轮播图图片数据
@adv_bp.route("/index_imgs", methods=['GET'])
def get_imgs():
    key = request.args.get('key')
    current_page = int(request.args.get('currentPage'))
    page_size = int(request.args.get('pageSize'))
    data = {
        'imgs': [],
        'total': 0,
        'meta': {
            'msg': 'success',
            'status': 200
        }
    }
    # 关键字搜索
    if key:
        imgs = AdvertiseImage.query.filter(or_(
            AdvertiseImage.text.contains(key),
            AdvertiseImage.desc.contains(key)
        )).paginate(current_page, page_size).items
    else:
        imgs = AdvertiseImage.query.paginate(current_page, page_size).items
    try:
        imgs = [{
            'id': i.id,
            'text': i.text,
            'is_online': i.is_online,
            'desc': i.desc,
            'url': i.img_url,
            'create_time': i.create_time.strftime('%Y-%m-%d %X'),
            'update_time': i.update_time.strftime('%Y-%m-%d %X'),
        } for i in imgs]
    except Exception as e:
        data['meta']['msg'] = 'fail'
        data['meta']['status'] = 400
        return jsonify(data)
    data['imgs'] = imgs
    data['total'] = len(imgs)
    return jsonify(data)


# 添加轮播图
@adv_bp.route("/add", methods=['POST'])
def add_img():
    data = {
        'imgs': [],
        'total': 0,
        'meta': {
            'msg': 'success',
            'status': 200
        }
    }
    form = request.json
    adv_img = AdvertiseImage(
        text=form.get('text'),
        is_online=int(form.get('is_online')),
        desc=form.get('desc'),
        img_url='http://192.168.56.1:9990/api/v1/img/' + form.get('img')
    )
    try:
        db.session.add(adv_img)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        traceback.print_exc()
        data['meta']['msg'] = 'fail'
        data['meta']['status'] = 400
    return jsonify(data)


# 图片上传接口
@adv_bp.route('/upload', methods=['POST'])
def upload():
    data = {
        'imgs': [],
        'total': 0,
        'meta': {
            'msg': 'success',
            'status': 200
        }
    }
    file_dir = os.path.join(app.config['BASE_URL'], app.config['UPLOAD_FOLDER'])
    if not os.path.exists(file_dir):
        os.makedirs(file_dir)
    try:
        img = request.files.get('file')
        img.save(os.path.join(file_dir, img.filename))
    except Exception as e:
        traceback.print_exc()
        data['meta']['msg'] = 'fail'
        data['meta']['status'] = 400
        return jsonify(data)
    return jsonify(data)


@adv_bp.route('/delete/<int:iid>', methods=['DELETE'])
def del_menu(iid):
    data = {
        'meta': {
            'msg': 'success',
            'status': 200
        }
    }
    try:
        img = AdvertiseImage.query.filter_by(id=iid).first()
        print(img)
        db.session.delete(img)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        traceback.print_exc()
        data['meta']['msg'] = 'fail'
        data['meta']['status'] = 400
        return jsonify(data)
    return jsonify(data)